﻿; (function (global) {

    'use strict';

    // pointing inside (column)
    //--5-1-46-3--49-5--64------7-------2-17--5--34-9-------2-4----7--56-32-48-1--4-2--
    // 2 in box 1 should be eliminated

    // pointing inside (row)
    //--9--8--6-6--3--9-7--6--4--4--7--5---7--5--24--5--4--8--63-1--2-3--2--6-8--9--3--
    // 6 in box 5 should be eliminated
    global.Strategies = global.Strategies || {};

    Strategies.PointingInside = function PointingInside() {
        this.type = 'elimination';
    }

    Strategies.PointingInside.prototype.perform = function (grid) {
        var result = this.performByRows(grid)
        if (result)
            return result;

        result = this.performByColumns(grid);
        if (result)
            return result;

        return null;
    }

    Strategies.PointingInside.prototype.performByRows = function (grid) {
        return this.performOnAlignedCells(grid, grid.cells);
    }

    Strategies.PointingInside.prototype.performByColumns = function (grid) {
        return this.performOnAlignedCells(grid, grid.cellsByColumn);
    }

    Strategies.PointingInside.prototype.performOnAlignedCells = function (grid, alignedCellsByIndex) {
        var containingCells = [];
        for (var i = 0; i < 9; i++) {
            var alignedCells = alignedCellsByIndex[i];
            for (var k = 1; k < 10; k++) {
                containingCells.clear();
                var regionId = null;
                for (var j = 0; j < 9; j++) {
                    var cell = alignedCells[j];
                    if (cell.candidates.has[k]) {
                        var cellRegionId = RegionHelper.computedRegions[cell.indices.i][cell.indices.j];
                        if (regionId === null) {
                            regionId = cellRegionId;
                        } else {
                            if (regionId !== cellRegionId) {
                                regionId = null;
                                break;
                            }
                        }
                        containingCells.push(cell);
                    }
                }

                if (regionId === null || containingCells.length === 1)
                    continue;

                var result = SolvingHelper.removeFromOtherCells(k, containingCells, grid.cellsByRegion[regionId])
                if (result) {
                    //console.log('pointing inside', k, regionIdOrNull);
                    return { candidate: k, containingCells: containingCells, targetCells: grid.cellsByRegion[regionId], lineCells: alignedCells };
                }
            }
        }
        return null;
    }

}(this));
